package news.utils.util;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
  
  
public class ObjectUtils {  
  
  
    /** 
     * 把r对象的所有属性拷贝到t对象中 
     * @param t 
     * @param r 
     */  
    public static <T, R> void copy(final T t, final R r) {  
        if (t != null && r != null) {  
            Field[] rfields = r.getClass().getDeclaredFields();  
            Field[] tfields = t.getClass().getDeclaredFields();  
            L: for (Field rfield : rfields) {  
                rfield.setAccessible(true);  
                for (Field tfield : tfields) {  
                    if (rfield.getName().equals(tfield.getName())) {  
                        tfield.setAccessible(true);  
                        try {  
                            tfield.set(t, rfield.get(r));  
                        } catch (Exception e) {  
                            continue L;  
                        }  
                    }  
                }  
            }  
        }  
    }  
    /** 
     * 把map对象的key-value拷贝到t对象中 
     * @param t 
     * @param r 
     */  
    public static <T> void copyWithMap(final T t, final Map<Object, Object> resMap) {  
        if (t != null && resMap != null) {  
            Field[] tfields = t.getClass().getDeclaredFields();  
            Iterator<Entry<Object, Object>> iterator = resMap.entrySet().iterator();  
            L: while (iterator.hasNext()) {  
                Entry<Object, Object> entry = iterator.next();  
                if (entry != null) {  
                    Object key = entry.getKey();  
                    Object value = entry.getValue();  
                    if (key != null && entry != null) {  
                        for (Field tfield : tfields) {  
                            if (key.toString().equals(tfield.getName())) {  
                                tfield.setAccessible(true);  
                                try {  
                                    tfield.set(t, value);  
                                } catch (Exception e) {  
                                    continue L;  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
        }  
    }  
  
  
}  